package com.naiterui.ehp.bs.patient.controller;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bp.bo.consult.CommentComplaintBO;
import com.naiterui.ehp.bp.bo.recommend.MedicationRecomPaBO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.constants.SwaggerTags;
import com.naiterui.ehp.bp.domain.ConsultSession;
import com.naiterui.ehp.bp.domain.Patient;
import com.naiterui.ehp.bp.support.context.ResourceHolder;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.support.security.SettingConfig;
import com.naiterui.ehp.bp.support.utils.IpUtil;
import com.naiterui.ehp.bp.utils.encypt.MD5;
import com.naiterui.ehp.bp.utils.event.EventUtil;
import com.naiterui.ehp.bp.utils.payment.bo.UnifiedOrderResultBO;
import com.naiterui.ehp.bs.patient.exception.ExceptionCodes;
import com.naiterui.ehp.bs.patient.feign.IDoctorFeignClient;
import com.naiterui.ehp.bs.patient.feign.RecomFeginClient;
import com.naiterui.ehp.bs.patient.handler.data.BizConfigEvent;
import com.naiterui.ehp.bs.patient.service.IConsultCommentService;
import com.naiterui.ehp.bs.patient.service.IConsultComplaintService;
import com.naiterui.ehp.bs.patient.service.IConsultSessionService;
import com.naiterui.ehp.bs.patient.service.IMedicationRecomService;
import com.naiterui.ehp.bs.patient.service.IPatientDoctorService;
import com.naiterui.ehp.bs.patient.service.IPatientService;
import com.naiterui.ehp.bs.patient.service.IVideoConsultService;
import com.naiterui.ehp.bs.patient.utils.constants.PatientConstant;
import com.naiterui.ehp.bs.patient.utils.exception.PatientBusinessException;
import com.naiterui.ehp.bs.patient.validation.ConsultSessionValidation;
import com.naiterui.ehp.bs.patient.validation.PatientValidation;
import com.naiterui.ehp.bs.patient.vo.AddVideoConsultVO;
import com.naiterui.ehp.bs.patient.vo.consult.ByConsultParamVO;
import com.naiterui.ehp.bs.patient.vo.consult.ConsultBillVO;
import com.naiterui.ehp.bs.patient.vo.consult.ConsultVO;
import com.naiterui.ehp.bs.patient.vo.consult.MedicationRecomVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 问诊业务控制器
 *
 * @author Amber
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("ap/patient")
@Api(tags = {SwaggerTag.PATIENT + SwaggerTag.CONSULT}, description = "问诊业务")
@Validated
@RequiredArgsConstructor
public class ApPatientConsultController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApPatientConsultController.class);

    /**
     * 会话是否有效key
     */
    private final String redisRepeatRequest = "patient_consult_status_";

    private final IPatientService patientService;

    private final IConsultSessionService consultSessionService;

    private final IMedicationRecomService medicationRecomService;

    private final IPatientDoctorService patientDoctorService;

    private final IVideoConsultService videoConsultService;

    @Autowired
    private IConsultCommentService consultCommentService;

    @Autowired
    private IConsultComplaintService consultComplaintService;
    @Autowired
    private RecomFeginClient recomFeginClient;
    @Autowired
    private IDoctorFeignClient doctorFeignClient;

    /**
     * im 回调key
     */
    private final String key = "aA6FWbrwHMkFCjNv";

    /**
     * 患者端，立即咨询、切换目标咨询医生
     *
     * @param patientId
     * @param doctorId
     * @return
     */
    @ApiOperation(tags = {SwaggerTags.WX_VIDEO_CONSULT}, value = "立即咨询、切换目标咨询医生", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("consult/chat")
    public ResponseVO<Integer> startChat(Long patientId, @NotNull(message = "医生ID不可为空") Long doctorId) {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        Integer result = patientDoctorService.startChat(patientId, doctorId);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, result);
    }

    /**
     * 图文咨询支付接口
     */
    @RequestMapping("consult/payinfo")
    @ApiOperation(value = "图文咨询支付接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "patientId", value = "患者ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "query")
    })
    public ResponseVO<UnifiedOrderResultBO> addPatientConsultPayInfo(Long patientId, Long doctorId, HttpServletRequest request,
        @RequestHeader("_o") Integer origin) throws Exception {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        String ip = IpUtil.getIp(request);
        LOGGER.info("图文咨询支付接口 请求参数 patientId {}, doctorId {} ip:{}", patientId, doctorId, ip);
        // 参数校验
        if (patientId == null || doctorId == null || StringUtils.isEmpty(ip)) {
            LOGGER.error("图文咨询支付接口 参数异常 patientId {}, doctorId {} ip:{}", patientId, doctorId, ip);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        UnifiedOrderResultBO result = consultSessionService.addPatientConsultPayInfo(patientId, doctorId, ip, origin);
        return PublicService.returnResponseVO(result);

    }

    /**
     * 患者端同意问诊协议
     *
     * @param patientId
     * @return
     */
    @PostMapping("consult/disclaimer")
    @ApiOperation( value = "患者端同意问诊协议", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "patientId", value = "患者id", required = true, dataType = "long", paramType = "query"),
        @ApiImplicitParam(name = "inquirerId", value = "就诊人id", required = true, dataType = "long", paramType = "query"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "query"),
        @ApiImplicitParam(name = "recordId", value = "记录id", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "consultType", value = "问诊类型, 1:图文咨询，2：视频咨询", required = true, dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "type", value = "病情记录类型, 1:病历,2:病情描述", required = true, dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "agree", value = "是否同意协议", required = true, dataType = "boolean", paramType = "query")
    })
    public ResponseVO<Integer> agreeDisclaimer(Long patientId,
        @NotNull(message = "就诊人ID") Long inquirerId,
        @NotNull(message = "医生ID不可为空") Long doctorId,
        String recordId,
        @NotNull(message = "问诊类型不可为空") Integer consultType,
        @NotNull(message = "患者病历类型不可为空") Integer type,
        Boolean agree) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        log.info("患者发起咨询问诊协议同意与否页面， patientId {}, doctorId {}, recordId {}, consultType {}, type {}, agree {}", patientId, doctorId, recordId,
            consultType, type, agree);
        Integer result = patientDoctorService.agreeDisclaimer(patientId, inquirerId, doctorId, type, recordId, agree, consultType);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, result);
    }

    /**
     * 患者填完病情发起咨询
     *
     * @param paramVO
     * @return
     * @throws BusinessException
     */
    @PostMapping("consult/start")
    @ApiOperation(tags = {
        SwaggerTags.WX_VIDEO_CONSULT}, value = "填写完病情之后准备开启会话(跳转支付或聊天窗口)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseVO<Integer> startConsult(Long patientId, @RequestBody ByConsultParamVO paramVO) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        paramVO.setPatientId(patientId);
        Integer result = patientDoctorService.startConsult(paramVO);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, result);
    }

    /**
     * 分页获取咨询记录列表 PatientConsultController.getMyConsultSessions()
     *
     * @param patientId
     * @param pageParam
     * @return
     * @Author Amber
     * @Date 2016年1月15日
     * @since 1.0.0
     */
    @RequestMapping("/consult/list")
    @ApiOperation(value = "分页获取咨询记录列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseVO<PageVO<ConsultVO>> getMyConsultSessions(Long patientId, PageParamVO pageParam) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        LOGGER.info("get consult list start patientId {}, PageParamVO {}", patientId, pageParam);
        // 参数校验
        if (patientId == null) {
            LOGGER.error("get consult list params error. patientId is null, pageParam {}", pageParam);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        PageVO<ConsultVO> consults = consultSessionService.getMyConsultSessions(patientId, pageParam.getPage(), pageParam.getNum());
        return PublicService.returnResponseVO(consults);
    }

    /**
     * 会话内推荐用药历史记录(患者端APP侧边栏-咨询记录-医生推荐用药 列表) PatientConsultController.getRecomDrugList()
     *
     * @param patientId
     * @param doctorId
     * @param consultId
     * @param pageParam
     * @return
     * @Author Amber
     * @Date 2016年2月26日
     * @since 1.0.0
     */
    @RequestMapping("recom/list")
    @ApiOperation(value = "会话内推荐用药历史记录", notes = "患者端APP侧边栏-咨询记录-医生推荐用药 列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public PageVO<MedicationRecomVO> getRecomDrugList(Long patientId, Long doctorId, Long consultId, PageParamVO pageParam) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        LOGGER.info("get recom drug list start patientId {},doctorId {}, consultId {}, pageParam {}", patientId, doctorId, consultId, pageParam);

        // 参数校验,consultId非必传，为空时查询全部推药记录
        if (patientId == null) {
            LOGGER.error("get recom drug list params error patientId null,consultId {}, pageParam {}", consultId, pageParam);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }

        return medicationRecomService.getRecomDrugList(patientId, doctorId, consultId, pageParam);
    }

    /**
     * 获取问诊记录评价信息 PatientConsultController.getAppraiseInfo()
     *
     * @param patientId
     * @param consultId
     * @return
     * @Author Amber
     * @Date 2016年2月27日
     * @since 1.0.0
     */

    @RequestMapping("consult/appraise/info")
    @ApiOperation(value = "获取问诊记录评价信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public ConsultBillVO getAppraiseInfo(Long patientId, Long consultId) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        LOGGER.info("get appraise info success patientId {}, consultId {}", patientId, consultId);
        // 参数校验
        if (patientId == null || consultId == null) {
            LOGGER.error("get appraise info params error patientId {}, consultId {}", patientId, consultId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        // 患者用户信息校验
        Patient patient = patientService.getPatient(patientId);

        // 用户信息校验
        PatientValidation.accountStatusValidate(patient, "get appraise info patientId:{}, consultId:{}", patientId, consultId);

        // 问诊信息校验
        ConsultSession session = consultSessionService.getConsultSessionById(consultId);

        // 问诊存在、已结束且属于该患者
        ConsultSessionValidation.validateForAppraise(session, patientId, "get appraise info patientId:{}, consultId:{}", patientId, consultId);

        ConsultBillVO consultBillVO = new ConsultBillVO();
        consultBillVO.setConsultId(consultId);
        consultBillVO.setStarsDesc(PatientConstant.STARS_DESC);
        consultBillVO.setHaveAppraise(session.getCommnetStatus() == ConsultSession.HAVE_COMMENT);
        return consultBillVO;

    }

    /**
     * 图文咨询收费信息页 PatientConsultController.getPatientConsultFee()
     *
     * @param patientId
     * @param doctorId
     * @return
     * @Author xuchong
     * @Date 2017年3月31日
     * @since 1.0.0
     */
    @RequestMapping("consult/fee")
    @ApiOperation(value = "", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> getPatientConsultFee(Long patientId, Long doctorId) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        LOGGER.info("get consult payInfo params patientId {}, doctorId {}", patientId, doctorId);

        // 参数校验
        if (patientId == null || doctorId == null) {
            LOGGER.error("get consult payInfo params patientId {}, doctorId {}", patientId, doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }

        return consultSessionService.getPatientConsultFee(patientId, doctorId);

    }


    /**
     * 校验图文咨询可否聊天接口 PatientConsultController.checkMessageConsultStatus()
     *
     * @return
     * @Author xuchong
     * @Date 2017年4月1日
     * @since 1.0.0
     */
    @RequestMapping("consult/status/check")
    @ApiOperation(value = "", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> checkMessageConsultStatus(Long patientId, Long doctorId) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        LOGGER.info("校验图文咨询可否聊天接口 请求参数 patientId {}, doctorId {}", patientId, doctorId);

        // 参数校验
        if (patientId == null || doctorId == null) {
            LOGGER.error("校验图文咨询可否聊天接口 参数异常 patientId {}, doctorId {}", patientId, doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        return consultSessionService.checkMessageConsultStatus(patientId, doctorId);
    }

    /**
     * <pre>
     *     无效会话
     * </pre>
     *
     * @param patientId 患者ID
     * @param doctorId  医生
     * @param sessionId 会话id
     * @return
     */
    @RequestMapping(value = "consult/invalid", method = RequestMethod.POST)
    public String consultInvalid(Long patientId, Long doctorId, String sessionId, String sign) throws Exception {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        LOGGER.info("会话无效请求参数：patientId = [{}], doctorId = [{}], sessionId = [{}], sign = [{}]", patientId, doctorId, sessionId, sign);
        if (patientId == null || doctorId == null || StringUtils.isEmpty(sessionId) || StringUtils.isEmpty(sign)) {
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        String signPara = "doctorId=" + doctorId + "&patientId=" + patientId + "&sessionId=" + sessionId + "&key=" + key;
        if (sign.equalsIgnoreCase(MD5.md5(signPara)) && !repeatRequest(sessionId)) {
            consultSessionService.updateConsultInvalid(patientId, doctorId, sessionId);
        } else {
            LOGGER.error("会话无效签名错误或重复请求：patientId = [{}], doctorId = [{}], sessionId = [{}], sign = [{}]", patientId, doctorId, sessionId, sign);
        }
        return "success";
    }

    /**
     * 校验会话结束消息是否可以评价或投诉
     * <pre>
     *     无效判断条件：
     *     1.消息超过24小时
     *     2.已评价
     *     3.已投诉
     * </pre>
     *
     * @param consultSessionId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "校验会话结束消息是否可以评价或投诉", tags = {SwaggerTags.WX_VIDEO_CONSULT})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "consultSessionId", value = "问诊会话id", dataType = "long", required = true, paramType = "query"),
        @ApiImplicitParam(name = "type", value = "问诊类型，1：图文问诊，2：视频问诊", dataType = "long", required = true, paramType = "query")
    })
    @RequestMapping(value = "consult/end/message/valid", method = RequestMethod.POST)
    public Boolean endMessageValid(Long consultSessionId, Integer type) throws BusinessException {
        /*if (consultSessionService.endMessageValid(consultSessionId, type)) {
            throw new BusinessException(ExceptionCodes.CONSULT_END_MESSAGE_EXPIRED);
        }*/
        if (consultCommentService.existByConsultSession(consultSessionId, type)) {
            throw new BusinessException(ExceptionCodes.CONSULT_END_MESSAGE_COMMENT_COMPLETE);
        }
        if (consultComplaintService.existByConsultSession(consultSessionId, type)) {
            throw new BusinessException(ExceptionCodes.CONSULT_END_MESSAGE_COMPLAINT_COMPLETE);
        }
        return true;
    }

    /**
     * 获取会话评价投诉详情
     *
     * @param consultSessionId
     * @param consultType
     * @return
     */
    @ApiOperation(value = "获取会话评价投诉详情", tags = {SwaggerTags.WX_VIDEO_CONSULT})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "consultSessionId", value = "问诊会话id", dataType = "long", required = true,
            paramType = "query"),
        @ApiImplicitParam(name = "type", value = "问诊类型，1：图文问诊，2：视频问诊", dataType = "long", required = true,
            paramType = "query")})
    @GetMapping("consult/getCommentComplaint")
    public CommentComplaintBO getCommentComplaint(@RequestParam("consultSessionId") Long consultSessionId,
        @RequestParam("consultType") Integer consultType) {
        return doctorFeignClient.getCommentComplaint(consultSessionId, consultType);
    }

    @ApiOperation(value = "免责协议开关", tags = {SwaggerTags.WX_PATIENT_COMPLAINT_COMMENTS})
    @ApiImplicitParam(name = "bizType", value = "开关：2：开，3：关", dataType = "int", required = true, paramType = "query")
    @RequestMapping(value = "consult/disclaimer/switch/{bizType}", method = RequestMethod.POST)
    public void disclaimerSwitch(@PathVariable Integer bizType) throws Exception {
        EventUtil.publishEvent(new BizConfigEvent("disclaimerSwitch", "", bizType));
    }


    /**
     * <pre>
     *     会话有效，增加积分
     * </pre>
     *
     * @param patientId 患者ID
     * @param doctorId  医生ID
     * @param sessionId 会话id
     * @return
     */
    @RequestMapping(value = "consult/vailability", method = RequestMethod.POST)
    public String consultValid(Long patientId, Long doctorId, String sessionId, String sign, Integer consultSourceType)
        throws PatientBusinessException {
        /*LOGGER.info("会话有效请求参数：patientId = [{}], doctorId = [{}], sessionId = [{}], sign = [{}],consultSourceType=[{}]", patientId, doctorId,
                    sessionId, sign, consultSourceType);
        if (patientId == null || doctorId == null || StringUtils.isAnyBlank(sessionId, sign) || consultSourceType == null) {
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        String signPara = "consultSourceType=" + consultSourceType + "&doctorId=" + doctorId + "&patientId=" + patientId + "&sessionId=" + sessionId
                + "&key=" + this.key;
        String paramSign = MD5.md5(signPara);
        if (sign.equalsIgnoreCase(paramSign) && !this.repeatRequest(sessionId)) {
            try {
                this.consultSessionService.updateConsultValid(patientId, doctorId, sessionId, consultSourceType);
            } catch (Exception e) {
                LOGGER.error("增加积分失败或发送账户动态失败 patientId = [{}], doctorId = [{}], sessionId = [{}]", patientId,
                        doctorId, sessionId, e);
            }
        } else {
            LOGGER.error("会话有效签名错误或重复请求：patientId = [{}], doctorId = [{}], sessionId = [{}], sign = [{}],pramsSign=[{}]", patientId, doctorId,
                         sessionId, sign, paramSign);
        }*/
        return "success";
    }

    /**
     * 是否重复请求，如果重复请求返回true 如果不是重复请求，返回false
     *
     * @param sessionId 会话ID
     * @return
     */
    private boolean repeatRequest(String sessionId) {

        String key = redisRepeatRequest + sessionId;

        Long incr = RedisUtil.keyOps().incr(key);

        if (incr > 1L) {
            LOGGER.info("重复请求，sessionId:{}", sessionId);
            return true;
        }

        // 过期时间设置十秒
        RedisUtil.keyOps().expire(key, 10);

        return false;

    }

    /**
     * 患者端，立即开始视频咨询
     *
     * @param patientId
     * @param doctorId
     * @return
     */
    @ApiOperation(tags = {SwaggerTags.WX_VIDEO_CONSULT}, value = "立即开始视频咨询", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("consult/video")
    public ResponseVO startVideo(Long patientId, @NotNull(message = "医生ID不可为空") Long doctorId)
        throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        return PublicService.returnResponseVO(videoConsultService.startVideo(patientId, doctorId));
    }

    /**
     * 视频咨询支付接口
     */
    @PostMapping("consult/video/payinfo")
    @ApiOperation(tags = {SwaggerTags.WX_VIDEO_CONSULT}, value = "视频咨询支付接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseVO<UnifiedOrderResultBO> addPatientVideoConsultPayInfo(Long patientId,
        AddVideoConsultVO addVideoConsultVO, HttpServletRequest request, @RequestHeader("_o") Integer origin)
        throws Exception {
        if (null == patientId) {
            patientId = (Long)ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        String ip = IpUtil.getIp(request);
        LOGGER.info("视频咨询支付接口 请求参数 patientId {}, addVideoConsultVO:{}, ip:{}", patientId, addVideoConsultVO, ip);
        // 参数校验
        if (patientId == null || addVideoConsultVO.getDoctorId() == null || StringUtils.isEmpty(ip)) {
            LOGGER.error("视频咨询支付接口 参数异常 patientId {}, addVideoConsultVO:{}, ip:{}", patientId, addVideoConsultVO, ip);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        UnifiedOrderResultBO result =
            videoConsultService.addPatientVideoConsultPayInfo(patientId, addVideoConsultVO, ip, origin);
        return PublicService.returnResponseVO(result);

    }

    /**
     * 患者处方列表
     *
     * @param patientId
     * @return
     * @throws BusinessException
     */
    @GetMapping("recommend/list")
    @ApiOperation(value = "患者处方列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "patientId", value = "患者ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "处方状态(0：待购买，1：已购买)", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "传 1 表示是续方申请页面", required = true, dataType = "int", paramType = "query"),

    })
    public PageVO<MedicationRecomPaBO> getPrescriptionList(Integer page, Integer num, Long patientId, Integer status,Integer type) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        log.info("获取患者处方列表，page {}, num {}, patientId {}, status {}, type {}", page, num, patientId, status ,type);
        return this.medicationRecomService.getPrescriptionList(page, num, patientId, status, type);
    }
}
